
var person = { name: '小明', age: 23}

person.greet = function() {
    console.log(`hello, my name is ${this.name}`)
}

person.greet()

var fn = function() {
    console.log(this)
}
fn()

// person.greetfn = function() {
//     return function() {
//         console.log(`hello, my name is ${this.name}`)
//     }
// }
// person.greetfn()()

// 闭包
person.greetfn2 = function() {
    var that = this
    return function() {
        console.log(`hello, my name is ${that.name}`)
    }
}
person.greetfn2()()

// 箭头函数
fn = x => x*x
console.log(fn(10))

person.greetfn3 = function() {
    return () => {
        // this 继承上层的this
        console.log(`hello, my name is ${this.name}`)
    }
}

person.greetfn3()()

// alert("hello")
//等价于
// window.alert("hello")

var a = 10
console.log(a)
// console.log(window.a)

// promise对象
// 异步编程, 回调函数
// function callback() {
//     console.log('Done')
// }
// console.log('before setTimeout()')
// setTimeout(callback, 1000) // 1s 后调用callback函数
// console.log('after setTimeout()')

function testResuletCallbackFunc(resolve, reject) {
    var timeOut = Math.random() * 2;
    console.log('set timeout to: ' + timeOut + ' seconds.');
    setTimeout(function () {
        if (timeOut < 1) {
            console.log('call resolve()...');
        resolve('200 OK');
        }
        else {
            console.log('call reject()...');
            reject('timeout in ' + timeOut + ' seconds.');
        }
    }, timeOut * 1000);
}

function testResuletCallback() {
    var success = (message) => {console.log('success ${message}')};
    var failed = (error) => {console.log('failed ${error}')};
    testResuletCallbackFunc(success, failed)
}

// testResuletCallback()

async function testWithAsync() {
    var p1 = new Promise(testResuletCallbackFunc)

    try {
        var resp = await p1
        console.log(resp);
    } catch (err) {
        console.log(err);
    }
}

testWithAsync()